package com.wandian.weather.mvvm.realweather.rainfallsituation;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.mvvm.BaseMVVMFragment;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.weather.bean.WeatherInformationBean;
import com.wandian.weather.databinding.WeatherFragmentRainSituationBinding;
import com.wandian.weather.tools.WeatherUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author Administrator
 * @date 2019/12/16-13:30
 * @description 降雨预报
 **/
public class RainSituationFragment extends BaseMVVMFragment<RainSituationViewModel> {

    private WeatherFragmentRainSituationBinding dataBinding;
    private String title;

    public static RainSituationFragment newInstance(String title) {
        Bundle args = new Bundle();
        args.putString("title", title);
        RainSituationFragment fragment = new RainSituationFragment();
        fragment.setArguments(args);
        return fragment;

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        dataBinding = WeatherFragmentRainSituationBinding.inflate(inflater);
        dataBinding.setLifecycleOwner(this);
        return dataBinding.getRoot();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        title = getArguments().getString("title");
        dataBinding.setViewModel(mViewModel);
        initViewData();
    }

    private void initViewData(){
        String weatherJson = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("WeatherInformationBean");
        if(UIUtils.isEmpty(weatherJson)){
            return;
        }
        WeatherInformationBean informationBean = JsonUtil.parseJsonToBean(weatherJson, WeatherInformationBean.class);
        if (informationBean != null) {
            List<Double> precipitation_2h = informationBean.getPrecipitation_2h();
            dataBinding.tvTemperatureTips.setText(informationBean.getMinutely_description());
            if(!UIUtils.isEmpty(informationBean.getBase())){
                dataBinding.ivTemperature.setImageResource(WeatherUtil.getWeatherStateImage(informationBean.getBase().getImg_num(), false));
            }
            initLineChart(precipitation_2h);
        }
    }

    private void initLineChart(List<Double> pres) {
        try {
            ArrayList<Entry> pointValues = new ArrayList<>();
            boolean haveData = false;

            final Map<Integer, String> xMap = new HashMap<>();
            final String[] valueArry = {"现在", "30分钟", "60分钟", "90分钟", "120分钟"};
            //下边if判断是为了使setLabelCount起作用：坐标数量/x轴标签数量 = 每个标签坐标数量，如果最后两个标签坐标数量相差大于对于5
            // setLabelCount就显示不正常，也就是每个label要大概平均分配setLabelCount才能正常显示设置的标签数量

            for (int i = 0; i < pres.size(); i++) {
                float yl = Float.parseFloat(String.valueOf(pres.get(i)));
                pointValues.add(new Entry(i, yl));
                if (yl != 0) haveData = true;
            }

            //设置没有数据时显示的文本
            dataBinding.chart.setNoDataText("没有数据喔~~");
            //设置是否绘制chart边框的线
//        lineChartView.setDrawBorders(true);
            //设置chart边框线颜色
//        lineChartView.setBorderColor(Color.GRAY);
            //设置chart边框线宽度
//        lineChartView.setBorderWidth(1f);
            //设置chart是否可以触摸
            dataBinding.chart.setTouchEnabled(false);
            //设置是否可以拖拽
            dataBinding.chart.setDragEnabled(false);
            //设置是否可以缩放 x和y，默认true
            dataBinding.chart.setScaleEnabled(false);
            //设置是否可以通过双击屏幕放大图表。默认是true
            dataBinding.chart.setDoubleTapToZoomEnabled(false);
            //设置chart动画
            dataBinding.chart.animateXY(1000, 1000);


            //=======================设置X轴显示效果==================
            XAxis xAxis = dataBinding.chart.getXAxis();
            //是否启用X轴
            xAxis.setEnabled(true);
            //是否绘制X轴线
            xAxis.setDrawAxisLine(true);
            //设置X轴上每个竖线是否显示
            xAxis.setDrawGridLines(false);
            //设置是否绘制X轴上的对应值(标签)
            xAxis.setDrawLabels(true);
            //设置X轴显示位置
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setTextColor(Color.parseColor("#80FFFFFF"));
            xAxis.setAxisLineColor(Color.WHITE);
            xAxis.setTextSize(14f);
            //设置竖线为虚线样式
            // xAxis.enableGridDashedLine(10f, 10f, 0f);
            //设置x轴标签数
            xAxis.setLabelCount(5, true);
            //图表第一个和最后一个label数据不超出左边和右边的Y轴
            // xAxis.setAvoidFirstLastClipping(true);

            //=================设置左边Y轴===============
            YAxis axisLeft = dataBinding.chart.getAxisLeft();
            //是否启用左边Y轴
            axisLeft.setEnabled(true);
            axisLeft.setDrawAxisLine(false);
            axisLeft.setTextColor(Color.parseColor("#80FFFFFF"));
            //设置最小值（这里就按demo里固死的写）
            axisLeft.setAxisMinimum(-0.1f);
            //设置最大值（这里就按demo里固死的写了）
            axisLeft.setAxisMaximum(0.5f);
            axisLeft.setLabelCount(3);
            axisLeft.setTextSize(14f);
            //设置横向的线为虚线
            axisLeft.enableGridDashedLine(5f, 5f, 0f);
            axisLeft.setGridColor(Color.parseColor("#80FFFFFF"));

            YAxis axisRight = dataBinding.chart.getAxisRight();
            axisRight.setEnabled(false);

            for (int i=0; i<pointValues.size(); i++){
                if (i == 0)
                    xMap.put((int) pointValues.get(i).getX(), valueArry[0]);
                else if (i < 30)
                    xMap.put((int) pointValues.get(i).getX(), valueArry[1]);
                else if (i < 60)
                    xMap.put((int) pointValues.get(i).getX(), valueArry[2]);
                else if (i < 90)
                    xMap.put((int) pointValues.get(i).getX(), valueArry[3]);
                else if (i < 120)
                    xMap.put((int) pointValues.get(i).getX(), valueArry[4]);
            }
            //自定义x轴标签数据
            xAxis.setValueFormatter(new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    return xMap.get((int) value);
                }
            });

            axisLeft.setValueFormatter(new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    if (value > 0.35f) return "大雨";
                    else if (value >= 0.15f && value <= 0.35f) return "中雨";
                    else return "小雨";
                }
            });

            Description description = new Description();
            description.setEnabled(false);
            //设置描述信息
            dataBinding.chart.setDescription(description);

            //点构成的某条线
            LineDataSet lineDataSet = new LineDataSet(pointValues, null);
            //设置该线的颜色
            if (haveData)
                lineDataSet.setColor(Color.WHITE);
            else
                lineDataSet.setColor(Color.parseColor("#00000000"));
            //设置每个点的颜色
//        lineDataSet.setCircleColor(Color.YELLOW);
            //设置该线的宽度
            lineDataSet.setLineWidth(2f);
            //设置每个坐标点的圆大小
            //lineDataSet.setCircleRadius(1f);
            //设置是否画圆
            lineDataSet.setDrawCircles(false);
            // 设置平滑曲线模式
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            //设置线一面部分是否填充颜色
//        lineDataSet.setDrawFilled(true);
            //设置填充的颜色
//        lineDataSet.setFillColor(Color.BLUE);
            //设置是否显示点的坐标值
            lineDataSet.setDrawValues(false);

            Legend l = dataBinding.chart.getLegend();//获取图例对象
            l.setEnabled(false);
            l.setForm(Legend.LegendForm.NONE);
            l.setTextColor(Color.parseColor("#ffffff"));
            dataBinding.chart.setExtraBottomOffset(20);
            dataBinding.chart.setExtraRightOffset(30);

            //线的集合（可单条或多条线）
            List<ILineDataSet> dataSets = new ArrayList<>();
            dataSets.add(lineDataSet);
            //把要画的所有线(线的集合)添加到LineData里
            LineData lineData = new LineData(dataSets);
            //把最终的数据setData
            dataBinding.chart.setData(lineData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
